// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const story_comment = db.collection("story_comment")
const tree_hole_story = db.collection("tree_hole_story")

// 云函数入口函数
//对文章发表评论
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { id, commentInfo } = event
  const result = await story_comment.where({ _id: id }).get()
  //该文章没有评论内容
  if (result.data.length === 0) {
    story_comment
      .add({
        data: {
          _id: id, _openid: wxContext.OPENID,
          comment: [commentInfo]
        }
      })
  } else {
    //文章已有评论内容
    let comment = result.data[0].comment
    comment.unshift(commentInfo)
    story_comment.doc(id)
      .update({
        data: { comment }
      })
  }
  //更新文章的评论数量
  const result2 = await tree_hole_story
    .where({ _id: id })
    .get()
  const reply_count = result2.data[0].reply_count + 1
  tree_hole_story
    .doc(id)
    .update({
      data: { reply_count }
    })
}